package com.tea.modules.java8.thread.atomic;

import com.tea.modules.java8.thread.annotation.ThreadSafe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author jaymin
 * @since 2022/2/19 21:58
 */
@ThreadSafe
@Slf4j
public class AtomicReferenceFieldUpdaterDemo {

    private static AtomicIntegerFieldUpdater<AtomicReferenceFieldUpdaterDemo> updater = AtomicIntegerFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterDemo.class, "count");
    /**
     * 必须用volatile修饰
     */
    @Getter
    public volatile int count = 100;

    private static AtomicReferenceFieldUpdaterDemo atomicReferenceFieldUpdater = new AtomicReferenceFieldUpdaterDemo();

    public static void main(String[] args) {
        // 会调用getCount()来比较
        if (updater.compareAndSet(atomicReferenceFieldUpdater, 100, 120)) {
            log.info("update success 1:{}", atomicReferenceFieldUpdater.count);
        }

        if (updater.compareAndSet(atomicReferenceFieldUpdater, 100, 120)) {
            log.info("update success 2:{}", atomicReferenceFieldUpdater.count);
        } else {
            log.info("update failed:{}", atomicReferenceFieldUpdater.count);
        }
    }
}
